#include <iostream>
#include <stdio.h>
#include <deque>
#include <string.h>

using namespace std;

int dx[4] = {0, 0, 1, -1}, dy[4] = {1, -1, 0, 0};
int R, C;
char a[300][300];
bool marked[300][300][3];

struct point {
	int x, y;
	int chamber; // chamber == 1, 2 or 3
	int step;
};

deque<point> q;
point start, end;

bool inside(point p)
{
	return ((0 <= p.x) && (p.x <= C-1) && (0 <= p.y) && (p.y <= R-1));
}


void BFS()
{
	while (!q.empty())
	{
		point u = q.front();

		q.pop_front();

		for (int i = 0; i < 4; i++)
		{
			point v;
			v.chamber = (u.chamber + 1) % 3;
			v.x = u.x + dx[i]*(v.chamber+1);
			v.y = u.y + dy[i]*(v.chamber+1);

			v.step = u.step+1;
			
			if (!inside(v)) continue;

			bool ok = true;
			for (int j = 1; j <= v.chamber+1; j++)
			{
				point t;
				t.x = u.x + dx[i]*j;
				t.y = u.y + dy[i]*j;
				if (a[t.y][t.x] == '#') 
				{
					ok = false;
					break;
				}
			}
			if (!ok) continue;

			if (!marked[v.y][v.x][v.chamber])
			{
				marked[v.y][v.x][v.chamber] = true;
				q.push_back(v);

				if (v.x == end.x && v.y == end.y)
				{
					cout << v.step << endl;
					return;					
				}
			}
		}
	}

	cout << "NO" << endl;
}

int main()
{
	int ntest;
	cin >> ntest;
	while (0 < ntest--)
	{
		scanf("%d %d\n", &R, &C);
		for (int r = 0; r < R; r++)
		{
			for (int c = 0; c < C; c++)
			{
				scanf("%c", &a[r][c]);
				if (a[r][c] == 'S')
				{
					start.x = c;
					start.y = r;
					start.chamber = 2;
					start.step = 0;
					a[r][c] = '.';
				}
				else
					if (a[r][c] == 'E')
					{
						end.x = c;
						end.y = r;
						end.chamber = 2;
						a[r][c] = '.';
					}
			}
			scanf("\n");
		}

		q.clear();
		q.push_back(start);
		memset(marked, false, sizeof(marked));
		marked[start.y][start.x][start.chamber] = true;

		BFS();
	}
	return 0;
}

